package com.empire.module.member.dal.mysql.user;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.empire.framework.common.pojo.PageResult;
import com.empire.framework.mybatis.core.mapper.BaseMapperX;
import com.empire.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.empire.module.member.controller.admin.user.vo.MemberUserPageReqVO;
import com.empire.module.member.dal.dataobject.user.MemberUserDO;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 会员 User Mapper
 *
 * @author 未来源码
 */
@Mapper
public interface MemberUserMapper extends BaseMapperX<MemberUserDO> {

    default MemberUserDO selectByIdcard(String idcard) {
        return selectOne(MemberUserDO::getIdcard, idcard);
    }

    @Select("select id from member_user where idcard like CONCAT('%', #{idNumber}, '%') or passport_number like CONCAT('%', #{idNumber}, '%')")
    List<Long> selectByIdNumber(@Param("idNumber") String idNumber);

    default MemberUserDO selectByPassportNumber(String passportNumber) {
        return selectOne(MemberUserDO::getPassportNumber, passportNumber);
    }

    default List<MemberUserDO> selectListByNicknameLike(String nickname) {
        return selectList(new LambdaQueryWrapperX<MemberUserDO>()
                .likeIfPresent(MemberUserDO::getNickname, nickname));
    }

    default PageResult<MemberUserDO> selectPage(MemberUserPageReqVO reqVO) {
        // 处理 tagIds 过滤条件
        String tagIdSql = "";
        if (CollUtil.isNotEmpty(reqVO.getTagIds())) {
            tagIdSql = reqVO.getTagIds().stream()
                    .map(tagId -> "FIND_IN_SET(" + tagId + ", tag_ids)")
                    .collect(Collectors.joining(" OR "));
        }
        if (CollUtil.isNotEmpty(reqVO.getTagIds())) {
            tagIdSql = reqVO.getTagIds().stream()
                    .map(tagId -> "FIND_IN_SET(" + tagId + ", tag_ids)")
                    .collect(Collectors.joining(" OR "));
        }
        // 分页查询
        return selectPage(reqVO, new LambdaQueryWrapperX<MemberUserDO>()
                .likeIfPresent(MemberUserDO::getPhoneNumber, reqVO.getPhoneNumber())
                .likeIfPresent(MemberUserDO::getNickname, reqVO.getNickname())
                .likeIfPresent(MemberUserDO::getIdcard, reqVO.getIdcard())
                .likeIfPresent(MemberUserDO::getPassportNumber, reqVO.getPassportNumber())
                .eqIfPresent(MemberUserDO::getDeptId, reqVO.getDeptId())
                .eqIfPresent(MemberUserDO::getForeigner, reqVO.getForeigner())
                .and(CollectionUtil.isNotEmpty(reqVO.getIdList()), wrapper -> {
                    if (reqVO.getIdList().size() == 1) {
                        wrapper.eq(MemberUserDO::getId, reqVO.getIdList().getFirst());
                    } else {
                        wrapper.in(MemberUserDO::getId, reqVO.getIdList());
                    }
                })
                .and(CollectionUtil.isNotEmpty(reqVO.getGroupIdList()), wrapper -> {
                    if (reqVO.getGroupIdList().size() == 1) {
                        wrapper.eq(MemberUserDO::getGroupId, reqVO.getGroupIdList().getFirst());
                    } else {
                        wrapper.in(MemberUserDO::getGroupId, reqVO.getGroupIdList());
                    }
                })
                .apply(StrUtil.isNotEmpty(tagIdSql), tagIdSql)
                .orderByDesc(MemberUserDO::getId));
    }

    default PageResult<MemberUserDO> selectCurInfoPage(MemberUserPageReqVO reqVO) {
        // 处理caseIds过滤条件，修正表别名引用问题
        if (StrUtil.isEmpty(reqVO.getCaseId())) {
            return selectPage(reqVO, new LambdaQueryWrapperX<>());
        }
        String subQuery = "select 1 from member_case_person_relation pcpr " +
                "where pcpr.case_id = {0} " +
                "and pcpr.person_id = member_user.id";  // 使用实际表名替代别名
        // 分页查询，使用exists条件并绑定参数
        return selectPage(reqVO, new LambdaQueryWrapperX<MemberUserDO>()
                .exists(subQuery, reqVO.getCaseId()));
    }

    default Long selectCountByGroupId(Long groupId) {
        return selectCount(MemberUserDO::getGroupId, groupId);
    }

    default Long selectCountByTagId(Long tagId) {
        return selectCount(new LambdaQueryWrapperX<MemberUserDO>()
                .apply("FIND_IN_SET({0}, tag_ids)", tagId));
    }

}
